package com.yss.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yss.constant.AuthConstants;
import com.yss.domain.LoginSysUser;
import com.yss.mapper.LoginSysUserMapper;
import com.yss.module.SecurityUser;
import com.yss.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @Description:商城后台管理系统登录策略的具体实现
 * @Author:yss
 * @Date:2024/7/23 21:40
 */

@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {
    @Autowired
    private LoginSysUserMapper loginSysUserMapper;
    @Override
    public UserDetails realLogin(String username) {
        //根据用户名称查询用户对象
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>()
                .eq(LoginSysUser::getUsername, username));
        if(ObjectUtil.isNotNull(loginSysUser)){
            // 根据用户标识查询用户权限集合
            Set<String> perms = loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());
            //创建安全用户对象SecurityUser
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setShopId(loginSysUser.getShopId());
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            //判断用户是否有权限
            if(CollectionUtil.isNotEmpty(perms)&&perms.size()!=0){
                securityUser.setPerms(perms);
            }
            return securityUser;
        }
        return null;
    }
}
